package com.greensam.pixelengine.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.*;
import com.greensam.pixelengine.exception.BusinessException;
import com.greensam.pixelengine.exception.ThrowUtils;
import com.greensam.pixelengine.pojo.emuns.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * url图片上传
 *
 * @author Macro_Ray
 * @since 2025/7/19 15:59
 */
@Slf4j
@Service
public class UrlPictureUpload extends PictureUploadTemplate {

    @Override
    protected void validPicture(Object inputSource) {
        String fileUrl = (String) inputSource;
        ThrowUtils.throwIf(fileUrl.isEmpty(), ErrorCodeEnum.ParamValidError, "文件不能为空");
        try {
            // 1. 初步验证 URL 格式
            new URL(fileUrl); // 验证是否是合法的 URL
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCodeEnum.ParamValidError, "文件地址格式不正确");
        }

        // 2. 校验 URL 协议
        ThrowUtils.throwIf(!(fileUrl.startsWith("http://") || fileUrl.startsWith("https://")),
                ErrorCodeEnum.ParamValidError, "仅支持 HTTP 或 HTTPS 协议的文件地址");

        // 3. 发送 HEAD 请求以验证文件是否存在
        try (HttpResponse response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute()) {
            // 未正常返回，无需执行其他判断
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            // 4. 校验文件类型
            String contentType = response.header("Content-Type");
            if (StringUtils.isNotBlank(contentType)) {
                // 允许的图片类型
                final List<String> allowContentTypes = Arrays.asList(
                        "image/jpeg", "image/jpg", "image/png", "image/webp");
                ThrowUtils.throwIf(!allowContentTypes.contains(contentType.toLowerCase()),
                        ErrorCodeEnum.ParamValidError, "文件类型错误：" + contentType);
            }
            // 5. 校验文件大小
            String contentLengthStr = response.header("Content-Length");
            if (StringUtils.isBlank(contentLengthStr)) {
                throw new BusinessException(ErrorCodeEnum.ParamValidError, "无法获取文件大小");
            }
            try {
                long contentLength = Long.parseLong(contentLengthStr);
                final long twoMb = 2 * 1024 * 1024L; // 限制文件大小为 2MB
                ThrowUtils.throwIf(contentLength > twoMb, ErrorCodeEnum.ParamValidError, "文件大小不能超过 2M");
            } catch (NumberFormatException e) {
                throw new BusinessException(ErrorCodeEnum.ParamValidError, "文件大小格式错误");
            }
        } catch (HttpException e) {
            log.error("HEAD 请求失败，URL: {}", fileUrl, e);
            throw new BusinessException(ErrorCodeEnum.ParamValidError, "无法访问文件地址");
        }
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        String fileUrl = (String) inputSource;
        return FileUtil.getName(fileUrl);
    }

    @Override
    protected void processFile(Object inputSource, File file) throws Exception {
        String fileUrl = (String) inputSource;
        // 下载图片到临时目录
        HttpUtil.downloadFile(fileUrl, file);
    }
}
